export function escapeStringHTML(str) {
  str = str.replace(/&lt;/g,'<')
  str = str.replace(/&gt;/g,'>')
  return str
}

export function myBrowser() {
  var userAgent = navigator.userAgent
  var isOpera = userAgent.indexOf('Opera') > -1
  if (isOpera) {
      return 'Opera'
  }
  if (userAgent.indexOf('Firefox') > -1) {
      return 'FF'
  }
  if (userAgent.indexOf('Chrome') > -1){
      return 'Chrome'
  }
  if (userAgent.indexOf('Safari') > -1) {
      return 'Safari'
  }
  if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) {
      return 'IE'
  }
  if (userAgent.indexOf('Trident') > -1) {
      return 'Edge'
  }
}

export function saveFile(response, fileName) {
  let filename = fileName
  let respHeader = response.headers['content-disposition']
  if (respHeader) {
    filename = window.decodeURI(respHeader.substring(respHeader.indexOf('filename=') + 10, respHeader.length - 1))
  }
  if (typeof window.chrome !== 'undefined' || myBrowser() == 'Safari') {
    let link = document.createElement('a')
    link.href = window.URL.createObjectURL(response.data)
    link.download = filename
    link.style.display = 'none'
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(link.href)
    document.body.removeChild(link)
  } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
      let blob = new Blob([response.data], { type: 'application/force-download' })
      window.navigator.msSaveBlob(blob, filename)
  } else {
      let file = new File([response.data], filename, { type: 'application/force-download' })
      window.open(URL.createObjectURL(file))
  }
}

export function randomString(length = 32) {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  const charLength = chars.length
  let result = ''
  for(let i = 0; i < length; i++) {
    result += chars[Math.floor(Math.random() * charLength)]
  }
  return result
}

export function imageIsExist(url) {
  return new Promise(resolve => {
    let img = new Image()
    img.onload = function () {
      if (this.complete == true) {
        resolve(true)
        img = null
      }
    }
    img.onerror = function () {
      resolve(false)
      img = null
    }
    img.src = url
  })
}